<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消费项目" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入消费项目"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消费类型" prop="itemType">
        <el-select v-model="queryParams.itemType" placeholder="请选择消费类型" clearable>
          <el-option
            v-for="dict in pond_consumption_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="鱼种" prop="fishTypeId">
        <el-select v-model="queryParams.fishTypeId" placeholder="请选择鱼种" clearable>
          <el-option
            v-for="fishType in fishTypes"
            :key="fishType.id"
            :label="fishType.name"
            :value="fishType.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pond:consumption:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pond:consumption:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pond:consumption:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="consumptionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" width="140" />
      <el-table-column label="消费项目" align="center" prop="itemName" width="150" />
      <el-table-column label="消费类型" align="center" prop="itemType" width="100">
        <template #default="scope">
          <dict-tag :options="pond_consumption_type" :value="scope.row.itemType"/>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" width="100">
        <template #default="scope">
          <span>¥{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="payStatus" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.payStatus === 1 ? 'success' : 'warning'">
            {{ scope.row.payStatus === 1 ? '已支付' : '未支付' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="payType" width="100">
        <template #default="scope">
          <span v-if="scope.row.payType === 1">微信</span>
          <span v-else-if="scope.row.payType === 2">支付宝</span>
          <span v-else-if="scope.row.payType === 3">现金</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['pond:consumption:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pond:consumption:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pond:consumption:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单消费记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="consumptionRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单" prop="orderId">
          <el-select v-model="form.orderId" placeholder="请选择订单" style="width: 100%" filterable>
            <el-option
              v-for="order in orderOptions"
              :key="order.orderId || order.id"
              :label="order.orderNo + ' - ' + order.userName"
              :value="order.orderId || order.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消费类型" prop="itemType">
          <el-select v-model="form.itemType" placeholder="请选择消费类型" @change="handleTypeChange">
            <el-option
              v-for="dict in pond_consumption_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消费项目" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入消费项目名称" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="0.001" :precision="3" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number v-model="form.unitPrice" :min="0.01" :precision="2" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount" :min="0.01" :precision="2" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item v-if="form.itemType === 'return'" label="鱼种" prop="fishTypeId">
          <el-select v-model="form.fishTypeId" placeholder="请选择鱼种">
            <el-option
              v-for="fishType in fishTypes"
              :key="fishType.id"
              :label="fishType.name"
              :value="fishType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.itemType === 'return'" label="鱼重量(kg)" prop="fishWeight">
          <el-input-number v-model="form.fishWeight" :min="0.001" :precision="3" placeholder="请输入鱼重量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 消费记录详情对话框 -->
    <el-dialog title="消费记录详情" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ detailInfo.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="消费类型">
          <dict-tag :options="pond_consumption_type" :value="detailInfo.itemType"/>
        </el-descriptions-item>
        <el-descriptions-item label="消费项目">{{ detailInfo.itemName }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ detailInfo.quantity }}</el-descriptions-item>
        <el-descriptions-item label="单价">¥{{ detailInfo.unitPrice }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ detailInfo.amount }}</el-descriptions-item>
        <el-descriptions-item v-if="detailInfo.fishTypeName" label="鱼种">{{ detailInfo.fishTypeName }}</el-descriptions-item>
        <el-descriptions-item v-if="detailInfo.fishWeight" label="鱼重量">{{ detailInfo.fishWeight }}kg</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailInfo.createBy }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailInfo.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Consumption">
import { listConsumption, getConsumption, delConsumption, addConsumption, updateConsumption } from "@/api/pond/consumption";
import { listOrder } from "@/api/pond/order";

const { proxy } = getCurrentInstance();
// 直接定义消费类型选项
const pond_consumption_type = ref([
  { value: 'fee', label: '钓费' },
  { value: 'shop', label: '商店' },
  { value: 'return', label: '回鱼' }
]);

const consumptionList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const orderOptions = ref([]);
const fishTypes = ref([]);
const detailInfo = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    itemName: null,
    itemType: null,
    fishTypeId: null,
  },
  rules: {
    orderId: [
      { required: true, message: "订单不能为空", trigger: "change" }
    ],
    itemType: [
      { required: true, message: "消费类型不能为空", trigger: "change" }
    ],
    itemName: [
      { required: true, message: "消费项目不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    unitPrice: [
      { required: true, message: "单价不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单消费记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != dateRange && '' != dateRange) {
    queryParams.value.params["beginTime"] = dateRange.value[0];
    queryParams.value.params["endTime"] = dateRange.value[1];
  }
  listConsumption(queryParams.value).then(response => {
    consumptionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    consumptionId: null,
    orderId: null,
    itemType: null,
    itemName: null,
    quantity: 1,
    unitPrice: null,
    amount: null,
    fishTypeId: null,
    fishWeight: null,
    remark: null
  };
  proxy.resetForm("consumptionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.consumptionId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getOrderOptions();
  open.value = true;
  title.value = "添加订单消费记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _consumptionId = row.consumptionId || ids.value
  getConsumption(_consumptionId).then(response => {
    form.value = response.data;
    getOrderOptions();
    open.value = true;
    title.value = "修改订单消费记录";
  });
}

/** 查看详情 */
function handleDetail(row) {
  getConsumption(row.consumptionId).then(response => {
    detailInfo.value = response.data;
    detailOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["consumptionRef"].validate(valid => {
    if (valid) {
      if (form.value.consumptionId != null) {
        updateConsumption(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addConsumption(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _consumptionIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单消费记录编号为"' + _consumptionIds + '"的数据项？').then(function() {
    return delConsumption(_consumptionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 获取订单选项 */
function getOrderOptions() {
  listOrder({ orderStatus: 1 }).then(response => {
    orderOptions.value = response.rows || [];
  });
}

/** 消费类型变化处理 */
function handleTypeChange(type) {
  if (type === 'return') {
    form.value.itemName = '回鱼收入';
  } else {
    form.value.itemName = '';
  }
}

/** 监听数量和单价变化，自动计算金额 */
watch([() => form.value.quantity, () => form.value.unitPrice], () => {
  if (form.value.quantity && form.value.unitPrice) {
    form.value.amount = (form.value.quantity * form.value.unitPrice).toFixed(2);
  }
});

onMounted(() => {
  getList();
  // 获取鱼种列表
  // getFishTypes().then(response => {
  //   fishTypes.value = response.data;
  // });
});
</script>